package com.gaojinqi.sys.core.shiro.rule;

import com.gaojinqi.base.common.enums.StateEnum;
import com.gaojinqi.sys.modular.rbac.dao.RolePermissionRepository;
import com.gaojinqi.sys.modular.rbac.model.RolePermissionMapping;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author gaojinqi
 * @version 1.0
 * @since 2020年05月12日
 */
@Service
public class ShiroFilterRulesProviderImpl implements ShiroFilterRulesProvider {

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Override
    public List<RolePermRule> findRolePermRules() {
        List<RolePermissionMapping> rolePermList = rolePermissionRepository.findRolePermsByState(StateEnum.ENABLE.getCode());
        // key：url，val：角色列表
        Map<String, Set<String>> rolePermMap = Maps.newLinkedHashMap();
        for (RolePermissionMapping mapping : rolePermList) {
            // url： 权限==请求方法，例如：user==post代表新增用户
            String url = mapping.getPerm().getUrl() + RolePermRule.SPLITTER + mapping.getPerm().getMethod().toUpperCase();
            Set<String> roles = rolePermMap.get(url);
            if (roles == null) {
                roles = Sets.newHashSet();
            }
            roles.add(mapping.getRole().getRole());
            rolePermMap.put(url, roles);
        }
        List<RolePermRule> rolePermRules = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(rolePermMap)) {
            for (Map.Entry<String, Set<String>> entry : rolePermMap.entrySet()) {
                String url = entry.getKey();
                Set<String> roles = entry.getValue();
                RolePermRule rolePermRule = new RolePermRule();
                rolePermRule.setUrl(url);
                rolePermRule.setNeedRoles(roles);
                rolePermRules.add(rolePermRule);
            }
        }
        return rolePermRules;
    }

}
